<?php
namespace app\admin\controller;

use app\admin\model\Article;
use app\admin\model\Catalog;
use app\admin\model\BookShelf;
use app\admin\model\BookCover;
use think\Image;
use think\Log;
use think\Request;

class Library extends Common
{
    private $bookshelf;
    private $bookcover;
    private $catalog;
    private $article;

    public function __construct()
    {
        parent::__construct();
        $this->bookshelf = new BookShelf();
        $this->bookcover = new BookCover();
        $this->catalog = new Catalog();
        $this->article = new Article();
    }

    public function index()
    {
        $bookshelf_info = $this->bookshelf->order('id')->select();
        $bookcover_info = $this->bookcover->order('id')->select();
        $this->assign('bookshelf_info', $bookshelf_info);
        $this->assign('bookcover_info', $bookcover_info);
        return $this->fetch();
    }

    public function addShelf()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $num = $this->bookshelf->allowField(true)->save($post);
                $post['id'] = $this->bookshelf->id;
                if ($num === 1) {
                    $result = [
                        'code' => E_OK,
                        'msg'  => '添加成功...',
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $post,
                    ];
                } else {
                    throw new \Exception("miss data to insert");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ADD_ITEM_FAILED,
                    'msg'  => '添加失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
                return $result;
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function updateShelf()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $num = $this->bookshelf->allowField(true)->isUpdate(true)->save($post);
                if ($num === 1) {
                    $result = [
                        'code' => E_OK,
                        'msg' => '更新成功...',
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $post,
                    ];
                } else {
                    throw new \Exception("no data to update");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_UPDATE_ITEM_FAILED,
                    'msg' => '更新失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        }  else {
            $this->redirect('admin/library/index');
        }
    }

    public function deleteShelfById()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $this->bookshelf->where(['id' => $post['id']])->delete();
                $coverids = $this->bookcover->field('id')->where(['shelf_id' => $post['id']])->select()->toArray();
                $coverids = array_column($coverids, 'id');
                $this->bookcover->where('id', 'in', $coverids)->delete();
                $this->catalog->where('cover_id', 'in', $coverids)->delete();
                $this->article->where('cover_id', 'in', $coverids)->delete();
                $path = config('coverimage.absolutepath') . DS . 'shelf_id_' . $post['id'];
                delDirAndFile($path);
                rm_empty_dir(config('coverimage.absolutepath'));
                $result = [
                    'code' => E_OK,
                    'msg' => '删除成功...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $post
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_DELETE_ITEM_FAILED,
                    'msg' => '删除失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        }  else {
            $this->redirect('admin/library/index');
        }
    }

    /*
     * 封面操作
     * */
    public function addCover()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $num = $this->bookcover->allowField(true)->save($post);
                $post['id'] = $this->bookcover->id;
                if ($num === 1) {
                    $result = [
                        'code' => E_OK,
                        'msg' => '添加成功...',
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $post,
                    ];
                    $file = request()->file('upload');
                    $uploadpath = config('coverimage.absolutepath') . DS . 'shelf_id_' . $post['shelf_id'] . DS . 'cover_id_' . $post['id'];
                    $savepath = config('coverimage.relativepath') . DS . 'shelf_id_' . $post['shelf_id'] . DS . 'cover_id_' . $post['id'];
                    $info_origin = $file->validate(['size' => config('coverimage.size'), 'ext' => config('coverimage.ext')])
                        ->move($uploadpath, "cover_origin");
                    if ($info_origin) {
                        $extension = '.'.$info_origin->getExtension();
                        $post['cover_pic_origin'] = $savepath . DS . "cover_origin".$extension;
                        Image::open(ROOT_PATH . 'public' . DS .$post['cover_pic_origin'])->thumb(64, 64)->save($uploadpath . DS . "cover_thumb".$extension);
                        $post['cover_pic_thumb'] = $savepath . DS . "cover_thumb".$extension;
                        $rows_ = $this->bookcover->allowField(['cover_pic_origin', 'cover_pic_thumb'])->isUpdate(true)->save($post);
                        if ($rows_ === 1) {
                            $result['data'] = $post;
                        } else {
                            unset($post['cover_pic_origin']);
                            unset($post['cover_pic_thumb']);
                            throw new \Exception("miss picture path info to insert");
                        }
                    } else {
                        // 上传失败获取错误信息???
                        $error_info_origin = $file->getError();
                    }
                } else {
                    throw new \Exception("miss data to insert");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ADD_ITEM_FAILED,
                    'msg' => '添加失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
                return $result;
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function updateCoverInfo()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $num = $this->bookcover->allowField(true)->isUpdate(true)->save($post);
                if ($num === 1) {
                    $result = [
                        'code' => E_OK,
                        'time' => $_SERVER['REQUEST_TIME'],
                        'msg' => '更新成功...',
                        'data' => $post,
                    ];
                } else {
                    throw new \Exception("no data to update");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_UPDATE_ITEM_FAILED,
                    'msg' => '更新失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function delCoverInfo()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            $this->bookcover->where('id', $post['id'])->delete();
            $this->catalog->where('cover_id', $post['id'])->delete();
            $this->article->where('cover_id', $post['id'])->delete();
            delDirAndFile(config('coverimage.absolutepath') . DS . 'shelf_id_' . $post['shelfid'] . DS . 'cover_id_' . $post['id']);
            rm_empty_dir(config('coverimage.absolutepath'));
            try {
                $result = [
                    'code' => E_OK,
                    'time' => $_SERVER['REQUEST_TIME'],
                    'msg' => '删除成功...',
                    'data' => $post
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_DELETE_ITEM_FAILED,
                    'msg' => '删除失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function uploadCoverImage()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $file = request()->file('upload');
                $uploadpath = config('coverimage.absolutepath') . DS . 'shelf_id_' . $post['shelf_id'] . DS . 'cover_id_' . $post['id'];
                $savepath = config('coverimage.relativepath') . DS . 'shelf_id_' . $post['shelf_id'] . DS . 'cover_id_' . $post['id'];

                $info_origin = $file->validate(['size' => config('coverimage.size'), 'ext' => config('coverimage.ext')])
                    ->move($uploadpath, "cover_origin");
                if ($info_origin) {
                    $extension = '.'.$info_origin->getExtension();
                    $post['cover_pic_origin'] = $savepath . DS . "cover_origin".$extension;
                    Image::open(ROOT_PATH . 'public' . DS .$post['cover_pic_origin'])->thumb(64, 64)->save($uploadpath . DS . "cover_thumb".$extension);
                    $post['cover_pic_thumb'] = $savepath . DS . "cover_thumb".$extension;
                    $rows_ = $this->bookcover->allowField(['cover_pic_origin', 'cover_pic_thumb'])->isUpdate(true)->save($post);
                    $result = [
                        'code' => E_OK,
                        'time' => $_SERVER['REQUEST_TIME'],
                        'msg' => '上传图片成功...',
                        'data' => $post,
                    ];
                } else {
                    // 上传失败获取错误信息
                    $error_info_origin = $file->getError();
                    Log::record($error_info_origin, 'error');
                    throw new \Exception("miss picture to upload: " + $error_info_origin);
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ADD_ITEM_FAILED,
                    'msg' => '上传图片失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
                Log::record($e->getMessage(), 'error');
                return $result;
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

}